package com.climber.android.commonsdk.helper

import android.annotation.SuppressLint
import android.view.View
import android.view.ViewTreeObserver
import com.google.android.material.appbar.AppBarLayout
import io.ganguo.library.klog.KLog

/**
 * Created by mikes on 2017-8-1.
 */

inline fun <T : View> T.afterMeasured(crossinline f: T.() -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        @SuppressLint("ObsoleteSdkInt")
        override fun onGlobalLayout() {
            if (measuredWidth > 0 && measuredHeight > 0) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                f()
            }
        }
    })
}

enum class CollapsingToolbarLayoutState {
    EXPANDED,           //状态标记为展开
    COLLAPSED,          //状态标记为折叠

    COLLAPSING,         //状态标记为折叠中
    EXPANDING           //状态标记为展开中
}

/**
 * verticalOffset 即AppBarLayout的位移距离，向上位移值减小，向下位移值增大。
 * 折叠中: verticalOffset 从0到 -(appBarLayout.totalScrollRange)变化，值逐渐减小
 *
 * 展开中：verticalOffset 从-(appBarLayout.totalScrollRange)到0变化，值逐渐增大
 */

inline fun <T : AppBarLayout> T.afterOffsetChanged(crossinline f: T.(state: CollapsingToolbarLayoutState) -> Unit) {
    var lastVerticalOffset = 0

    this.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
        if(appBarLayout != null){
            var state: CollapsingToolbarLayoutState? = null
            if (verticalOffset == 0) {//修改状态标记为展开
                if (state != CollapsingToolbarLayoutState.EXPANDED) {
                    state = CollapsingToolbarLayoutState.EXPANDED
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.totalScrollRange) { //修改状态标记为折叠
                if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                    state = CollapsingToolbarLayoutState.COLLAPSED
                }
            } else {
                if(verticalOffset > lastVerticalOffset){
                    // 展开中
                    state = CollapsingToolbarLayoutState.EXPANDING
                } else{
                    // 折叠中
                    state = CollapsingToolbarLayoutState.COLLAPSING
                }
            }

            lastVerticalOffset = verticalOffset

            f(state)
        }
    })
}
